package com.hailian.fintech.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.hailian.fintech.autoconfig.AlipayProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
@Slf4j
public class AlipayService {

    private AlipayProperties alipayProperties;

    public AlipayService(AlipayProperties alipayProperties){
            this.alipayProperties = alipayProperties;
    }

    /**
     * 支付宝统一下单
     * @param orderNo
     * @return
     * @throws AlipayApiException
     */
    public Object pay(String orderNo) throws AlipayApiException {

        DefaultAlipayClient alipayClient = initDefaultAlipayClient();
//        AlipayClient alipayClient = new DefaultAlipayClient(payConfig.getUrl(), payConfig.getAppid(), payConfig.getAppPrivateKey(), "json", "utf-8", payConfig.getAlipayPublicKey(), "RSA2");

        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
        Map<String,String> maps = new HashMap<String,String>();
        maps.put("out_trade_no",orderNo);
        maps.put("total_amount","3.0");
        maps.put("subject","可口可乐");
        maps.put("store_id","NJ_001");
        maps.put("timeout_express","3600m");
        request.setBizContent(JSON.toJSONString(maps));
        //设置回调的url地址 关键
        request.setNotifyUrl(alipayProperties.getCallBackUrl());
        AlipayTradePrecreateResponse response = alipayClient.certificateExecute(request);
        System.out.print(response.getBody());
        String qrcode = response.getQrCode();
        return qrcode;

    }

    /**
     *  查询订单状态
     *      *  交易状态：WAIT_BUYER_PAY（交易创建，等待买家付款）、
     *      *  TRADE_CLOSED（未付款交易超时关闭，或支付完成后全额退款）、
     *      *  TRADE_SUCCESS（交易支付成功）、
     *      *  TRADE_FINISHED（交易结束，不可退款）
     * @param orderNo
     * @return
     * @throws AlipayApiException
     */
    public Object queryOrderStatus(String orderNo) throws AlipayApiException {

        DefaultAlipayClient alipayClient = initDefaultAlipayClient();

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
        JSONObject json = new JSONObject();
        json.put("out_trade_no", orderNo);
        request.setBizContent(json.toString());
        AlipayTradeQueryResponse   response = alipayClient.certificateExecute(request);
        if(response.isSuccess()){
           // System.out.println("调用成功");
            log.info("调用成功");
            return response.getTradeStatus();
        } else {
//            System.out.println("调用失败");
            log.info("调用失败");
            return null;
        }



    }

    /**
     * 实现支付宝对账
     * @param
     * @return response
     */
    public void alipayBill(){
        log.info("==================向支付宝发起对账请求");
        try {

            DefaultAlipayClient alipayClient = initDefaultAlipayClient();

            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();//创建API对应的request类
           /* request.setBizContent("{" +
                    "\"bill_type\":\"trade\"," +
                    "\"bill_date\":\"2020-06-01\"}"); //设置业务参数*/
            JSONObject json = new JSONObject();
            json.put("bill_type", "trade");
            json.put("bill_date", new DateTime().minusDays(1).toString("yyyy-MM-dd"));
            request.setBizContent(json.toString());
            AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.certificateExecute(request);

            String billDownloadUrl=response.getBillDownloadUrl();
            log.info("==================支付宝返回文件下载地址："+billDownloadUrl);
            this.downBill(billDownloadUrl); //调用下载文件方法

        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }//通过alipayClient调用API，获得对应的response类

        //根据response中的结果继续业务逻辑处理

    }
//        2.获取到支付宝返回的订单文件下载地址之后，我们直接把它下载到本地，下载的代码如下：

    /**
     * 下载账单文件：
     * @param
     * @return response
     */
    public String downBill(String billDownloadUrl){
        long filename=new Date().getTime();
        //指定希望保存的文件路径
        String filePath = "e:/alipay/"+filename+".zip";
        URL url = null;
        HttpURLConnection httpUrlConnection = null;
        InputStream fis = null;
        FileOutputStream fos = null;
        try {
            url = new URL(billDownloadUrl);
            httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setConnectTimeout(5 * 1000);
            httpUrlConnection.setDoInput(true);
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setUseCaches(false);
            httpUrlConnection.setRequestMethod("GET");
            httpUrlConnection.setRequestProperty("Charsert", "UTF-8");
            httpUrlConnection.connect();
            fis = httpUrlConnection.getInputStream();
            byte[] temp = new byte[1024];
            int b;
            fos = new FileOutputStream(new File(filePath));
            while ((b = fis.read(temp)) != -1) {
                fos.write(temp, 0, b);
                fos.flush();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fis!=null) fis.close();
                if(fos!=null) fos.close();
                if(httpUrlConnection!=null) httpUrlConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    //实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型）
    public DefaultAlipayClient initDefaultAlipayClient() throws AlipayApiException {
        CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
        certAlipayRequest.setServerUrl(alipayProperties.getUrl());
        certAlipayRequest.setAppId(alipayProperties.getAppid());
        certAlipayRequest.setPrivateKey(alipayProperties.getAppPrivateKey());
        certAlipayRequest.setFormat("json");
        certAlipayRequest.setCharset("utf-8");
        certAlipayRequest.setSignType("RSA2");
        certAlipayRequest.setCertPath(alipayProperties.getAppCertPath());

        certAlipayRequest.setAlipayPublicCertPath(alipayProperties.getAlipayCertPath());
        certAlipayRequest.setRootCertPath(alipayProperties.getAlipayRootCertPath());
        return  new DefaultAlipayClient(certAlipayRequest);
    }


}
